from django.shortcuts import render
import markdown
from django.http import HttpResponse
import os
import re
from .models import MarkdownFile
from django.shortcuts import get_object_or_404
from django.http import JsonResponse

def replace_image_paths(html_content, new_path_prefix="/static/tu/"):
    """
    替换HTML内容中图片的src路径。
    
    :param html_content: 原始HTML内容字符串
    :param new_path_prefix: 新的路径前缀
    :return: 替换后的HTML内容字符串
    """
    # 示例HTML内容
    # html_example = '<img src="/old/path/测试项.png" alt="测试图片">'
    # '<img alt="测试项" src="/old/path/测试项.png">'
    # test = r'</h2><p><img src="E:\\xuexi-ziliao\\zjx\\1\\tcp客户端，服务端.png" referrerpolicy'
    img_pattern = r'<img[^>]*src="([^"]+)"'  # 正则表达式，使用捕获组匹配src属性的值
    matches = re.findall(img_pattern, html_content)
    
    for match in matches:
        file_name = os.path.basename(match)
        match_path = re.search(r'\\([^\\]+)$', file_name)
        if match_path:
            file_name = match_path.group(1)  # 返回匹配到的文件名
        print(file_name)
        new_path = new_path_prefix + file_name
        
        # 直接在原始正则基础上进行替换，确保捕获组正确应用
        html_content = re.sub(r'src="' + re.escape(match) + '"', f'src="{new_path}"', html_content)
    
    return html_content

def markdown_list(request):
    # MarkdownFile模型有file_name字段存储文件名，content字段存储转换后的HTML内容
    all_files = MarkdownFile.objects.all()
    return render(request, 'note_web/markdown_list.html', {'all_files': all_files})

def content_by_filename(request, filename):
    markdown_file = get_object_or_404(MarkdownFile, file_name=filename)
    new_html = replace_image_paths(markdown_file.content_html)
    return JsonResponse({'content': new_html}, safe=False)

def index(request):
    return render(request, 'note_web/index.html')

def display_markdown(request, filename):
       # 指定Markdown文件的存储路径，这里以与views.py同级的'md_files'目录为例
       md_file_path = os.path.join(os.path.dirname(__file__), 'md_files', filename + '.md')
       print(md_file_path)
       # 检查文件是否存在
       if not os.path.exists(md_file_path):
           return HttpResponse("File not found.", status=404)
       
       # 读取Markdown文件内容
       with open(md_file_path, 'r') as file:
           content = file.read()
       
       # 将Markdown转换为HTML
       html_content = markdown.markdown(content)

       # 替换HTML内容中图片的src路径。
       new_html = replace_image_paths(html_content)

       # 将HTML内容传递给模板
       return render(request, 'note_web/markdown_template.html', {'content': new_html})









